package Sort;

public class sortColors {
//    1. 两次遍历方法
    public void sortColors(int[] nums) {
        int length = nums.length;
        int[] count = new int[3];
        for (int i = 0; i < length; i++) {
            if (nums[i] == 0) {
                count[0] += 1;
            } else if (nums[i] == 1) {
                count[1] += 1;
            } else {
                count[2] += 1;
            }
        }
        int k = 0;
        for (int i = 0; i <= 2; i++) {
            int temp = count[i];
            while (temp > 0) {
                nums[k] = i;
                k++;
                temp--;
            }
        }
    }

// 2. 波兰国旗解法
    public void sortColors1(int[] nums) {
//        0的最右边界
        int p0 = 0;
//        当前指针指向位置
        int curr = 0;
//        2的最左边界
        int p2 = nums.length - 1;
        int temp;
        while (curr <= p2) {
            if (nums[curr] == 0) {
                temp = nums[p0];
                nums[p0++] = nums[curr];
                nums[curr++] = temp;
            } else if (nums[curr] == 2) {
                temp = nums[p2];
                nums[p2--] = nums[curr];
                nums[curr++] = temp;
            } else {
                curr++;
            }
        }
    }
}
